﻿// vim: set ft=javascript fileencoding=utf-8 bomb et:
// Demo file. 
// author: elia
// update: 2016-02-09

// Define `Slider' here:

// func_get: return a number in percent
// func_get: return nothing while has ONE argument - pos
var Slider = function(func_get, func_set) {
	this.is_drag = false;
	this.get = (function () {
		return typeof func_get == "function" ? func_get : function() {};
	})();
	this.set = (function () {
		return typeof func_set == "function" ? func_set : function () {};
	})();
	this.pos = this.get();
}

Slider.prototype.draw = function(gr, x, y, w, h, active_color, inactive_color) {
	gr.FillSolidRect(x, y, w, h, inactive_color);
	if (this.pos > 0 && this.pos <= 1) {
		gr.FillSolidRect(x, y, w * this.pos, h, active_color);
	}
	this.x = x;
	this.y = y;
	this.w = w;
	this.h = h;
}

Slider.prototype.is_mouse_over = function(x, y) {
	return (x > this.x && x < this.x + this.w && y > this.y && y < this.y + this.h);
}

Slider.prototype.down = function(x, y) {
	if (this.is_mouse_over(x, y)) {
		this.is_drag = true;
		this.move(x, y);
	}
}

Slider.prototype.up = function(x, y) {
	this.is_drag = false;
}

Slider.prototype.move = function(x, y) {
	if (this.is_drag) {
		x -= this.x ;
		this.pos = x < 0 ? 0 : x > this.w ? 1 : x / this.w;
		this.set(this.pos);
		window.Repaint();
	}
}

Slider.prototype.update = function() {
	this.pos = this.get();
	window.Repaint();
}

			
// others

function pos2vol(pos) {
	return (50 * Math.log(0.99 * pos + 0.01) / Math.LN10);
};

function vol2pos(v) {
	return ((Math.pow(10, v / 50) - 0.01) / 0.99);
};

//
var ww = 0,
	wh = 0;

var sk, vl;

//
//
sk = new Slider(
		function() {
			return fb.PlaybackTime / fb.PlaybackLength;
		}, 
		function (pos) {
			fb.PlaybackTime = fb.PlaybackLength * pos;
		});

vl = new Slider(
		function () {
			return vol2pos(fb.Volume);
		},
		function (pos) {
			fb.Volume = pos2vol(pos);
		});

// callbacks

function on_size() {
	ww = window.Width;
	wh = window.Height;
}

function on_paint(gr) {
	sk.draw(gr, 10, 10, ww - 20, 10, 0xff000000, 0x10000000);
	vl.draw(gr, 10, 40, 150, 10, 0xff000000, 0x10000000);
}

function on_mouse_move(x, y) {
	if (fb.IsPlaying) {
		sk.move(x, y);
	}
	vl.move(x, y);
}

function on_mouse_lbtn_down(x, y) {
	if (fb.IsPlaying) {
		sk.down(x, y);
	}
	vl.down(x, y);
}

function on_mouse_lbtn_up(x, y) {
	sk.up(x, y);
	vl.up(x, y);
}

function on_volume_change(val) {
	vl.update();
}

function on_playback_starting() {
	sk.update();
}

function on_playback_stop(reason) {
	if (reason != 2) {
		sk.update();
	}
}

function on_playback_time() {
	sk.update();
}
